import React, { useEffect, useMemo, useRef } from 'react'
import MarkdownIt from 'markdown-it'
import Prism from 'prismjs'
import 'prismjs/themes/prism-okaidia.css' // 引入 PrismJS 的样式进行代码高亮
import MdMermaid from 'mermaid-it-markdown'
import MdLinkAttributes from 'markdown-it-link-attributes'
import { copyToClip } from '../../utils/copy'
import Texmath from 'markdown-it-texmath'
import Katex from 'katex'
import 'katex/dist/katex.min.css' // 引入 KaTeX 的样式

const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true,
  highlight: (str, lang) => highlightBlock(str, lang)
})

function highlightBlock(str: string, lang?: string) {
  const language = lang && Prism.languages[lang] ? lang : 'javascript' // 默认语言
  const highlighted = Prism.highlight(str, Prism.languages[language], language)
  return `<pre class="code-block-wrapper language-${language}"><div class="code-block-header"><span class="code-block-header__lang">${lang}</span><span class="code-block-header__copy">复制</span></div><code class="hljs code-block-body ${language}">${highlighted}</code></pre>`
}

md.use(MdLinkAttributes, { attrs: { target: '_blank', rel: 'noopener' } }) // a标签在新窗口打开
  .use(MdMermaid) // 支持流程图、时序图、类图、甘特图等
  .use(Texmath, {
    engine: Katex, // 指定渲染引擎为 katex
    delimiters: 'brackets' // 使用 'brackets' 定界符预设，支持 \(...\) 和 \[...\]
  })

interface MarkdownRendererProps {
  markdownContent: string
}

const MarkdownRenderer: React.FC<MarkdownRendererProps> = ({ markdownContent }) => {
  const rootRef = useRef<HTMLDivElement>(null)

  useEffect(() => {
    const root = rootRef.current
    if (!root) return

    const handleClick = (e: MouseEvent) => {
      const target = e.target as HTMLElement
      if (target.classList.contains('code-block-header__copy')) {
        const copyBtn = target
        const codeElement = copyBtn.closest('.code-block-header')?.nextElementSibling
        if (codeElement) {
          const code = codeElement.textContent as string
          copyToClip(code).then(() => {
            copyBtn.textContent = '复制成功'
            setTimeout(() => {
              copyBtn.textContent = '复制'
            }, 1000)
          })
        }
      }
    }

    root.addEventListener('click', handleClick)
    return () => root.removeEventListener('click', handleClick)
  }, [])

  const htmlContent = useMemo(() => {
    if (!markdownContent) return ''
    return md.render(markdownContent)
  }, [markdownContent])

  return (
    <div ref={rootRef} className="markdown-body">
      {htmlContent && <div dangerouslySetInnerHTML={{ __html: htmlContent }} />}
    </div>
  )
}

// 导出一个名为 renrenMarkdown 的函数，该函数接收一个字符串类型的参数 content
export function renrenMarkdown(content: string) {
  // 返回一个 MarkdownRenderer 组件，并将 content 作为 markdownContent 属性传递给该组件
  return <MarkdownRenderer markdownContent={content} />
}

export default MarkdownRenderer
